package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class BackWork2 extends Activity {
	TextView mResult;
	AccumThread mThread;
	ProgressDialog mProgress;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		mResult = (TextView) findViewById(R.id.ch19_result);
	}

	public void mOnClick(View v) {
		int start = 0, end = 100;
		mProgress = new ProgressDialog(this);
		mProgress.setTitle("Calculating");
		mProgress.setMessage("Now calculating");
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setCancelable(false);
		mProgress.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				mThread.mQuit = true;
				mProgress.dismiss();
			}
		});
		mProgress.show();
		mThread = new AccumThread(start, end, mAfterAccum);
		mThread.start();
	}

	class AccumThread extends Thread {
		int mStart, mEnd;
		int mResult;
		Handler mAfter;
		boolean mQuit;

		AccumThread(int start, int end, Handler after) {
			mStart = start;
			mEnd = end;
			mQuit = false;
			mAfter = after;
		}

		public void run() {
			mResult = 0;
			for (int i = mStart; i <= mEnd; i++) {
				mResult += i;
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					;
				}
				if (mQuit) {
					return;
				}
			}
			mAfter.sendEmptyMessage(0);
		}
	}

	Handler mAfterAccum = new Handler() {
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			if (mThread.mQuit == false) {
				mResult.setText("" + mThread.mResult);
			}
		}
	};
}